package com.example.qecode.controller;

import com.example.qecode.pojo.User;
import com.example.qecode.service.QECodeService;
import com.example.qecode.service.QECodeServiceImpl;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.decoder.QRCodeDecoderMetaData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class QECodeControllere {
    @Autowired
    QECodeService qeCodeService;
    @Autowired
    QECodeServiceImpl qeCodeServiceImpl;

    // http://127.0.0.1:8080/save_user?name=newName&age=11
    @RequestMapping("/createqecode")
    @ResponseBody
    public void createQE() throws IOException, WriterException {
        qeCodeService.createQE();
    }

    @RequestMapping("/decode")
    @ResponseBody
    public ResponseEntity<String> decodeQRCode() throws ChecksumException, NotFoundException, IOException, WriterException, FormatException {
        return ResponseEntity.ok(qeCodeService.decode());
    }

    @PostMapping("/decode2")
    public ResponseEntity<String> decodeQRCode(@RequestParam("aaa") MultipartFile file) {
        try {
            // 读取上传的图片
            BufferedImage image = ImageIO.read(file.getInputStream());

            // 调用二维码解析方法
            String qrCodeContent = qeCodeServiceImpl.decodeQRCode(image);

            return ResponseEntity.ok(qrCodeContent); // 返回二维码内容
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("二维码解析失败: " + e.getMessage());
        }
    }
}
